<?php

namespace app\admin\controller\integral;

use app\common\controller\Backend;
use app\admin\model\AuthDepartment;
use fast\Tree;

/**
 * 任务管理
 *
 * @icon fa fa-circle-o
 */
class Core extends Backend
{
    
    /**
     * Core模型对象
     * @var \app\admin\model\Core
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Core;
        $dept = GetBaseInfo('Dept');
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id','in',''.implode(',',$dept).'')->whereOr('parentid','in',''.implode(',',$dept).'')->select())->toArray();
        Tree::instance()->init($groupList);
        //权限
        $this->RoleFinance = GetRoleFinance();
        $groupdata = [];
        $result = [];
        if(!empty($this->RoleFinance['role'])){
            $groups = $this->auth->getGroups();
            $userid = \think\Session::get('admin')['userid'];
            $temp = [];
            foreach (explode(',',$this->RoleFinance['role']) as $m => $n){
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(2));
                if($n == 2){
                    foreach ($childlist as $k => $v){
                        if(ValueExists($dept,$v['id'])){
                            $kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
                            $kee = implode(',',array_column($kee,'id'));
                            $temp[$kee] = $v['name'];
                            unset($kee);
                        }else{
                            $temp[$v['id']] = $v['name'];
                        }
                    }
                }else{
                    foreach ($childlist as $k => $v){
                        if(ValueExists($dept,$v['id'])){
                            if($v['id'] == $n || $v['parentid'] == $n) {
                                $kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
                                $kee = implode(',',array_column($kee,'id'));
                                $temp[$kee] = $v['name'];
                                unset($kee);
                            }
                        }else{
                            if($v['id'] == $n || $v['parentid'] == $n) $temp[$v['id']] = $v['name'];
                        }
                    }
                }
            }
            $groupdata = $temp;
        }
        //print_r($groupdata);die;
        $this->view->assign('groupdata', $groupdata);
        $start_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['start_time'];
        $end_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['end_time'];
        $this->view->assign("DefaultsTime", $start_time.','.$end_time);
        $this->view->assign("DefaultsDate", date('Y'));
        $this->view->assign("DefaultsDateM", date('m'));
        $this->view->assign("Generate_Week", \think\Config::get('finance.Generate_Week'));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $date=$this->request->post("date");
                    list($starttime,$endtime)=(explode(',',$date));

                    $params['starttime']=$starttime;
                    $params['endtime']=$endtime;
                    if ($this->model->where(array('department'=>$params['department'],'starttime'=>$starttime,'endtime'=>$endtime))->find()){
                        $this->error("当前分公司本周已分配任务！");

                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $date=$this->request->post("date");
                    list($starttime,$endtime)=(explode(',',$date));

                    $params['starttime']=$starttime;
                    $params['endtime']=$endtime;
                    if ($this->model->where(array('department'=>$params['department'],'id'=>!$ids,'starttime'=>$starttime,'endtime'=>$endtime))->find()){
                        $this->error("当前分公司本周已分配任务！");

                    }

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['department','week','id','person','starttime','endtime','text','inputtime','user']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
}
